<template>
  <div>
    <a-modal :title="checkType == 0 ? $t('Set-quick-range') : $t('Set-deep-range')" :visible="visible" width='40%'
      @ok="handleOk" @cancel="handleCancel" :cancelText="$t('Cancel')" :okText="$t('Starting-check')"
      :maskClosable='false' :ok-button-props="{ props: { disabled: selectDiskNum == 0 } }" v-dragModal>
      <div class="tip">
        <img src="../../../../../static/images/disk_check/16_f_ic_tips.png" alt="tip_img" />
        <span v-if="$store.state.language == 'zh'">您一共选择了<span
            class="disk-num">{{ selectDiskNum }}块</span>磁盘，磁盘选得越多，检测时间越长，如希望快速出结果，建议单次选择较少磁盘，分批检测。</span>
        <span v-else>You selected <span class="disk-num">{{ selectDiskNum }}</span> disks, the more disks you select, the
          longer the detection time will be. To obtain quick results, you are advised to select fewer disks at a time and
          check in batches. </span>
      </div>
      <a-tree v-model="checkedKeys" checkable show-icon defaultExpandAll :selected-keys="selectedKeys"
        :tree-data="treeData" @check="onCheck">
        <template slot="parent" slot-scope="{ halfChecked, checked}">
          <!-- {{scope}} -->
          <img v-if="checked || halfChecked" src="../../../../../static/images/disk_check/16_f_ic_disk_selected.png"
            alt="disk_selected_img" />
          <img v-else src="../../../../../static/images/disk_check/16_f_ic_disk_normal.png" alt="disk_normal_img" />
        </template>
        <template slot="child" slot-scope="{ checked }">
          <img v-if="checked" src="../../../../../static/images/disk_check/ic_Networkdisk_selected.png"
            alt="net_disk_img" />
          <img v-else src="../../../../../static/images/disk_check/ic_Networkdisk_normal.png" alt="net_disk_normal_img" />
        </template>
      </a-tree>
    </a-modal>
  </div>
</template>

<script>
import request from '@/request/request'

export default {
  name: "SelectDiskDialog",
  props: {
    visible: {
      type: Boolean
    },
    checkType: {
      type: Number
    },
    checkDisks: {}
  },
  data() {
    return {
      checkedKeys: [],
      selectedKeys: [], //选中的节点
      treeData: [
        {
          title: this.$t('System-disk'),
          key: 'system_disks',
          scopedSlots: { icon: 'parent' },
          children: [
            // {title: '0-1',key: '0-01',scopedSlots: { icon: 'child' }},
          ],
        },
        {
          title: this.$t('Cache-disk'),
          key: 'cache_disks',
          scopedSlots: { icon: 'parent' },
          children: [
            // { title: '0-1-0-0', key: '0-1-0-0',scopedSlots: { icon: 'child' }},
          ],
        },
        {
          title: this.$t('Data-disk'),
          key: 'data_disks',
          scopedSlots: { icon: 'parent' },
          children: [
            // { title: '0-1-0-0', key: '0-1-0-0',scopedSlots: { icon: 'child' }},
          ],
        },
        {
          title: this.$t('No-active-disk'),
          key: 'inactive_disks',
          scopedSlots: { icon: 'parent' },
          children: [
            // { title: '0-1-0-0', key: '0-1-0-0',scopedSlots: { icon: 'child' }},
          ],
        }
      ],
      allSelectNum: 0,//三个磁盘类别全部选中的数量
      hostnameArr: [],
      tasks: [],
    }
  },
  watch: {
    visible(newValue) {
      //将磁盘数据格式化
      if (newValue) {
        this.treeData[0].children = [];
        this.treeData[1].children = [];
        this.treeData[2].children = [];
        this.treeData[3].children = [];
        if (this.checkDisks.cache_disk && this.checkDisks.cache_disk.length != 0) {
          this.checkDisks.cache_disk.forEach(item => {
            let obj = {};
            obj.title = item.hostname + " " + item.name + " " + this.judgeDiskType(item.type) + " " + item.avail + this.getDiskDesc(item);
            obj.key = item.hostname + '-' + item.wwid;
            obj.scopedSlots = { icon: 'child' };
            this.treeData[1].children.push(obj);
          })
        }
        if (this.checkDisks.data_disk && this.checkDisks.data_disk.length != 0) {
          this.checkDisks.data_disk.forEach(item => {
            let obj = {};
            obj.title = item.hostname + " " + item.name + " " + this.judgeDiskType(item.type) + " " + item.avail + this.getDiskDesc(item);
            obj.key = item.hostname + '-' + item.wwid;
            obj.scopedSlots = { icon: 'child' };
            this.treeData[2].children.push(obj);
          })
        }
        if (this.checkDisks.sys_disk && this.checkDisks.sys_disk.length != 0) {
          this.checkDisks.sys_disk.forEach(item => {
            let obj = {};
            obj.title = item.hostname + " " + item.name + " " + this.judgeDiskType(item.type) + " " + item.avail + this.getDiskDesc(item);
            obj.key = item.hostname + '-' + item.wwid;
            obj.scopedSlots = { icon: 'child' };
            this.treeData[0].children.push(obj);
          })
        }
        if (this.checkDisks.free_disk && this.checkDisks.free_disk.length != 0) {
          this.checkDisks.free_disk.forEach(item => {
            let obj = {};
            obj.title = item.hostname + " " + item.name + " " + this.judgeDiskType(item.type) + " " + item.avail + this.getDiskDesc(item);
            obj.key = item.hostname + '-' + item.wwid;
            obj.scopedSlots = { icon: 'child' };
            this.treeData[3].children.push(obj);
          })
        }
      }
    },
    getlanguage() {
      this.treeData[0].title = this.$t('System-disk');
      this.treeData[1].title = this.$t('Cache-disk');
      this.treeData[2].title = this.$t('Data-disk');
      this.treeData[3].title = this.$t('No-active-disk');
    }
  },
  computed: {
    selectDiskNum() {
      //因为全选的时候会把父节点算上，所有到时要减去
      //如果里面包含'系统盘'、'缓存盘'、'数据盘'字段，
      this.allSelectNum = 0;
      this.selectedKeys.forEach((item, i) => {
        let index = -1;
        if (item == 'system_disks' || item == 'data_disks' || item == 'cache_disks' || item == 'inactive_disks') {
          index = i;
        }
        if (index != -1) {
          this.allSelectNum++;
        }
      })
      return this.selectedKeys.length - this.allSelectNum;
    },

    getlanguage() {
      return this.$store.state.language
    }
  },
  methods: {
    //开始检测
    handleOk() {
      // console.log('checkedKeys', this.checkedKeys)
      this.checkedKeys.forEach(item => {
        let index = 0;
        let node = '';
        index = item.indexOf('-');
        node = item.substring(0, index);
        this.hostnameArr.push(node);
      })
      this.hostnameArr = Array.from(new Set(this.hostnameArr));
      for (const item of this.hostnameArr) {
        let obj = {
          hostname: item,
          disks: []
        }
        this.checkedKeys.forEach(subItem => {
          let index = 0;
          let node = '';
          index = subItem.indexOf('-');
          node = subItem.substring(0, index);
          if (node == item) {
            let wwid = '';
            wwid = subItem.substring(index + 1);
            obj.disks.push(wwid);
          }
        })
        this.tasks.push(obj);
      }
      // for (let i = 0; i < this.hostnameArr.length; i++) {
      //   let obj = {
      //     hostname: this.hostnameArr[i],
      //     disks: []
      //   }
      //   this.checkedKeys.forEach(item => {
      //     let index = 0;
      //     let node = '';
      //     index = item.indexOf('-');
      //     node = item.substring(0, index);
      //     if (node == this.hostnameArr[i]) {
      //       let wwid = '';
      //       wwid = item.substring(index + 1);
      //       obj.disks.push(wwid);
      //     }
      //   })
      //   this.tasks.push(obj);
      // }
      // this.handleCancel();
      // this.$emit('isCheckingDisk', true);
      // this.getCheckStatus()
      request('post', 'diskhealth/disks_scan', {
        type: this.checkType,
        task: this.tasks
      }).then(res => {
        // console.log('开始检测了', res)
        // this.handleCancel();
        // this.$emit('isCheckingDisk', true);
        // this.model(res.data.id) //返回模板
        // this.notice(res.data.id,res.data.params,res.data.flag) //通知列表显示
        if (res.data.success) {
          this.handleCancel();
          this.$emit('isCheckingDisk', true);
          // this.getCheckStatus();
          this.$message.success(this.$t('Disk-start-check'));
        } else {
          this.$message.error(this.$t('Disk-start-check-fail'));
        }
      }).catch(err => {
        console.log(err);
      }).finally(() => {
        this.handleCancel();
      })
    },

    //磁盘描述(最近检测：时间+模式)
    getDiskDesc(item) {
      if (item.start_time) {
        let des = ''
        if (item.scan_type == 0) des = this.$t('Quick-check')
        else if (item.scan_type == 1) des = this.$t('Deep-check')
        return `（${this.$t('Recent-detection')}：${item.start_time} ${des}）`
        // return `（${this.$t('Recent-detection')}：${item.start_time} ${item.scan_type == 0 ? this.$t('Quick-check') : item.scan_type == 1 ? this.$t('Deep-check') : ''}）`
      } else {
        return `（${this.$t('Recent-detection')}：${this.$t('Nothing')}）`
      }
    },

    //实时获取检测状态
    // getCheckStatus() {
    //   this.$axios.get(this.allurl + 'diskhealth/health/real_time').then(res => {
    //     if(res.data.success) {
    //       this.$emit('updateCheckingInfo', {
    //         use_time: res.data.use_time,
    //         percent: res.data.percent,
    //         check_type: res.data.check_type
    //       })
    //     }
    //   }).catch(err => {
    //     console.log(err);
    //   })
    // },

    //关闭弹窗
    handleCancel() {
      this.$emit('closeDialog');
      this.checkedKeys = [];
      this.selectedKeys = [];
      this.hostnameArr = [];
      this.tasks = [];
    },

    //磁盘选中
    onCheck(selectedKeys) {
      // console.log('selectedKeys', selectedKeys)
      this.selectedKeys = selectedKeys;
    },

    //判断是什么类型的盘
    judgeDiskType(type) {
      if (type == 1) {
        return 'HDD'
      } else {
        return 'SSD'
      }
    },
  }
}
</script>

<style scoped>
.tip {
  padding: 15px;
  background-color: rgba(7, 133, 253, 0.1);
  border-radius: 4px;
  border: solid 1px var(--themeColor);
}

.tip img {
  margin-right: 5px;
}

.disk-num {
  color: var(--themeColor)
}

.ant-tree {
  height: 367px;
  overflow: auto;
}

@media screen and (min-width:1920px) {
  .ant-tree {
    height: 520px;
    overflow: auto;
  }
}
</style>